package com.zatom.newscore.utils;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SyncLimitedThreadPoolExecutor extends ThreadPoolExecutor {
    private static final Logger log = LoggerFactory.getLogger(com.zatom.newscore.utils.SyncLimitedThreadPoolExecutor.class);

    public SyncLimitedThreadPoolExecutor(int corePoolSize, Integer MaxQueue, String ThreadName) {
        super(corePoolSize, corePoolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(MaxQueue.intValue()), (ThreadFactory) new NamedThreadFactory(ThreadName, true));
    }

    public SyncLimitedThreadPoolExecutor(int corePoolSize) {
        super(corePoolSize, corePoolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), (ThreadFactory) new NamedThreadFactory("SyncThreadPoolExecutor", true));
    }

    public SyncLimitedThreadPoolExecutor(int corePoolSize, String ThreadName) {
        super(corePoolSize, corePoolSize, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(200), (ThreadFactory) new NamedThreadFactory(ThreadName, true));
    }

    public void execute(Runnable command) {
        try {
            while (true) {
                if (getQueue().remainingCapacity() > 0) {
                    super.execute(command);
                    return;
                }
                Thread.sleep(200L);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            try {
                Thread.sleep(200L);
            } catch (Exception e2) {
                log.error(e.getMessage(), e);
            }
            return;
        } catch (Throwable $ex) {
            throw $ex;
        }
    }

    public void waitForFinish() {
        try {
            while (true) {
                if (getActiveCount() == 0)
                    return;
                Thread.sleep(200L);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            try {
                Thread.sleep(200L);
            } catch (Exception e2) {
                log.error(e.getMessage(), e);
            }
            return;
        } catch (Throwable $ex) {
            throw $ex;
        }
    }
}
